<?php
  require_once("includes/overhead.php");
	$allow = false;
	$successfulSections = 0;
	$line = 0;
	$duplicates = 0;
	$count = 0;
	session_start(); 
	if(isset($_REQUEST['logout'])){
    unset($_SESSION['loggedin']);
    session_destroy();
  }
  if(!$_SESSION['loggedin']){
    if(!isset($_POST['pass'])){
      $content = "<h3>Please Login</h3><form method='POST'>Enter password: " .
          "<input type='password' name='pass' /><input type='submit' value='Login' /></form>";
    }else{
      if($_POST['pass'] == 'justice1885'){
				$allow = true;
				$_SESSION['loggedin'] = true;
			}
		}
	}else{
    $allow = true;
  }
	if($allow){
		if(isset($_FILES["dataFile"])){
			if($_FILES["dataFile"]["error"] > 0){
				$error = "Error importing Registrar File.";
			}else{
        $checkImportQuery = mysql_query("select ID, Name,TimeRun from Import " . 
            "where FileName='" . $_FILES["dataFile"]['name'] . "'");
				$row = mysql_fetch_assoc($checkImportQuery);
				if($row){
          $error = "File with name " . $_FILES["dataFile"]['name'] . 
              " has already been imported under the title '" . $row['Name'] . "' at " . $row['TimeRun'] . ".<br />";
        }else{
				 	$fileRead = fopen($_FILES["dataFile"]["tmp_name"], "r");
					//get first line but don't do anything with it (just contains headers)
					$count=0;
	 				while(!feof($fileRead)){
	 					$s = new Section();
	 					$selection = fgets($fileRead);
						$data = (explode("\t", str_replace('"', '', $selection)));
						if(($data[0]=="Term") || ($data[0] == null) || ($data[0] == "")){
              $count++;
              continue;
            }
						//$checkDupsQuery=mysql_query("select ID from Section where Term
						if(false){
              $duplicates++;
              continue;
            }
						$t = new Term();
						if(!$t->retrieveFromYearMonth($data[0])){
							$t->setBasedOnYearMonth($data[0]);
							if(!$t->insert()){
                $error = "ERROR CREATING TERM.";
                break;
              }
						}
						$sizeNoW = str_replace("%", "", $data[5]) + str_replace("%", "", $data[6]) + 
                str_replace("%", "", $data[7]) + str_replace("%", "", $data[8]) + str_replace("%", "", $data[9]);
				 		$size = $sizeNoW+$data[13];
				 		if($sizeNoW ==0){
              $count++;
              continue;
            }
						$d = new Department();
						$c = new Course();		
						$p = new Professor();
	
						//Check to see that Department exists
						if(!$d->retrieveFromCode(substr($data[1], 0, strpos($data[1], " ")))){
              //If it doesn't, create it.
							$d->setCode(substr($data[1], 0, strpos($data[1], " ")));
							$d->setName("");
							if(!$d->insert()){
								$error = "COULD NOT CREATE DEPARTMENT WITH CODE '" . $data[0] . "'";
								break;
							}
					 	}
					 	if($data[4] == ""){
              $count++;
              continue;
            }
						if($row = mysql_fetch_assoc(mysql_query("select ID from Professor where LastName='" . 
                mysql_real_escape_string(substr($data[4], 0, strpos($data[4], ","))) . "' and FirstName='" . 
                mysql_real_escape_string(substr($data[4], strpos($data[4], ",") + 1)) . "'"))){
							$p->retrieveFromID($row['ID']);
							}else{ 
								$p->setFirstName(mysql_real_escape_string(substr($data[4],strpos($data[4],",")+1)));
								$p->setLastName(mysql_real_escape_string(substr($data[4],0,strpos($data[4],","))));
								$p->insert();
							}
							$query = mysql_query("select ID from Course where Number=" . $bill = substr($data[1], strpos($data[1], " ")) . " and DepartmentID=" . $d->getID()) or die(mysql_error());
					 		if(mysql_num_rows($query) != 0){
                $row = mysql_fetch_assoc($query);
					 			$c->retrieveFromID($row['ID']);
					 		}else{
					 			$c->setDepartment($d);
					 			$c->setNumber(substr($data[1], strpos($data[1], " ")));
					 			$c->setDescription("");
					 			$c->setName("");
					 			if(!$c->insert()){
                  $error = "ERROR INSERTING COURSE.";
                  break;
                }
					 		}
	
					 		$s->setCRN($data[3]);
					 		$s->setCode($data[2]);
					 		$s->setPercent_A(($data[5] != " " ? str_replace("%", "", $data[5]) : 0) / $size*100);
					 		$s->setPercent_B(($data[6] != " " ? str_replace("%", "", $data[6]) : 0) / $size*100);
					 		$s->setPercent_C(($data[7] != " " ? str_replace("%", "", $data[7]) : 0) / $size*100);
					 		$s->setPercent_D(($data[8] != " " ? str_replace("%", "", $data[8]) : 0) / $size*100);
					 		$s->setPercent_F(($data[9] != " " ? str_replace("%", "", $data[9]) : 0) / $size*100);
					 		$s->setPercent_W(($data[13] != " " ? str_replace("%", "", $data[13]) : 0) / $size*100);
					 		$s->setProfessor($p);
					 		$s->setCourse($c);
					 		$s->setTerm($t);
					 		$getSizeQuery = mysql_query("select ID from SectionSize where Description='" . $data[15] . "'");
					 		$row = mysql_fetch_assoc($getSizeQuery);
					 		$s->setSize($row['ID']);
					 		$s->setGPA((($data[5] != " " ? str_replace("%", "", $data[5]) : 0) * 4 + 
                  ($data[6] != " " ? str_replace("%", "", $data[6]) : 0) * 3 + 
                  ($data[7] != " " ? str_replace("%", "", $data[7]) : 0) * 2 + 
                  ($data[8] != " " ? str_replace("%", "", $data[8]) : 0)) / $sizeNoW);
              $s->setSurvey(0);
					 		if(!$s->insert()){
					 			$error = "ERROR INSERTING SECTION " . $s->getCRN() . " [" . $t->getSemester() . 
                    " " . $t->getYear() . "]";
					 		}else{
                $successfulSections++;
					 		}
					 	}
            $createImportQuery = mysql_query("insert into Import " . 
                "(FileName, TimeRun, Name, RowsInserted, RowsIgnored, DuplicateRows) " .
                "values ('" . $_FILES["dataFile"]['name'] . "', NOW(), '" . $_REQUEST['importName'] . 
                "', " . $successfulSections . ", " . $count . ", " . $duplicates . ")");
            if(!$createImportQuery){
              $error = "Error creating import record!";
            }
					} 
				}
			}
			if(isset($_FILES["ciosFile"])){
				if($_FILES["ciosFile"]["error"] > 0){
					$error = "Error importing CIOS File.";
				}else{ 
					$fileRead = fopen($_FILES["ciosFile"]["tmp_name"], "r");
					//get first line but don't do anything with it (just contains headers)
					$count = 0;
					$successfulSections = 0;
	 				while(!feof($fileRead))	{
	 					$selection = fgets($fileRead);
	 					$data = (explode("\t", str_replace('"', '', $selection)));
	 					if(($data[0] == "Term") || ($data[0] == null) || ($data[0] == "")){
              $count++;
              continue;
            }
	 					$t = new Term();
						if(!$t->retrieveFromYearMonth($data[0])){
							$error="TERM NOT FOUND."; break; 
						}
						$profLastName = substr($data[5], 0, strrpos($data[5], ","));
						$getProfessorIDQuery = mysql_query("select P.ID as PID from Professor as P join Section as S on P.ID=S.ProfessorID where P.LastName like '" . 
                mysql_real_escape_string($profLastName) . "%' and S.CRN=" . $data[1] . " and S.Code='" . $data[4] . "'");
						//print "[select P.ID as PID from Professor as P join Section as S on P.ID=S.ProfessorID where P.LastName='".$profLastName."' and S.CRN=".$data[1]." and S.Code='".$data[4]."']";
						$profRow = mysql_fetch_assoc($getProfessorIDQuery);
						if($profRow){
							if($addSurveyQuery = mysql_query("update Section set Survey=1 where CRN=" . $data[1] . " and TermID=" . $t->getID() . " and ProfessorID=" . $profRow['PID'])){
								$successfulSections++;
							}else{
                $error = "Error updating Survey flag. Professor:" . $profLastName . ",CRN:" . $data[1];
              }
						}else{
              $count++;
            }
	 				}
				}
			}
		
			$content = "<h3>Administration Panel</h3><a href='admin.php?logout=1'>LOGOUT</a><br /><p><strong>Please upload <u>only one file at a time.</u></strong></p>\n" . 
          (isset($error) ? $error . "." : "") . " Successful:" . $successfulSections . ". Error on Line: " . $line . ". Skipped lines: " . $count . 
          ". Skipped Duplicates: " . $duplicates . "<br />\n<h4>Import Registrar Data</h4><p><small>This area allows you to import a .tab file from the Registrar's " . 
          "office containing <strong>grade distributions</strong>,<strong>section information</strong> and <strong>course descriptions</strong>.</small><br />\n" . 
          "<form method='POST' enctype='multipart/form-data' action='admin.php'>\nData file: <br /><input type='file' name='dataFile' id='dataFile' /><br />\n" . 
          "Term: <br />\n<input type='text' name='importName' /><small> (ie: 'Fall 2009')</small><br />\n<br />\n<input type='submit' value='Load Registrar Data' />\n" . 
          "</form>\n</p>\n<h4>Import CIOS Survey Data</h4><p><small>This area allows you to import a .tab file from CETL containing <strong>a list of course sections " . 
          "having a survey</strong></small><br />\n<form method='POST' enctype='multipart/form-data' action='admin.php'>\nData file: <br />\n" . 
          "<input type='file' name='ciosFile' id='ciosFile' /><br />\n<br />\n<input type='submit' value='Load CIOS Data' />\n</form>\n</p>";
		}
    $pageTitle="Administrative Panel";
    $breadcrumbs[0]['URL']='index.php';
    $breadcrumbs[0]['Title']='Course Critique';
    $breadcrumbs[1]['URL']='data.php';
    $breadcrumbs[1]['Title']='Data';
    $didYouKnow['Title']='What happened?';
    $didYouKnow['Content']="Wow! Things look a little different, huh? Did you know your <a href='http://sga.gatech.edu/undergraduate/executive/get-involved/it-committee'> " . 
    "Information Technology Committee</a> has been working diligently to bring you an <strong>improved, more reliable Course Critique? But we're <strong>not done yet!</strong>" . 
    " We still need <strong>your</strong> feedback!</strong>";
    include("views/stdPage.php");
?>